import { computed, defineComponent, type ExtractPropTypes } from 'vue';

import _template from 'lodash/template';
import { ItemTemplateGeneralType } from '../interface';
import './resultItem.scss';
import Style from './resultItem.module.scss';
// Components
import TextEllipsis from './text-ellipsis/TextEllipsis';
import TImg from 't/basic/img';
import TIcon from 't/basic/icon';


export const resultItemProps = {
  itemTemplateGeneral: {
    type: Array<ItemTemplateGeneralType>,
    default: () => [
      {
        type: 'title',
        valueType: '',
        field: '',
        expression: '',
        ellipsis: true,
        demo: '',
      },
      {
        type: 'thumb',
        valueType: '',
        field: '',
        expression: '',
        ellipsis: false,
        demo: '',
      },
      {
        type: 'info',
        valueType: '',
        field: '',
        expression: '',
        ellipsis: true,
        demo: '',
      },
      {
        type: 'info',
        valueType: '',
        field: '',
        expression: '',
        ellipsis: true,
        demo: '',
      },
    ],
  },
  data: {
    type: Object, // 指定类型为对象
    default: () => ({}), // 设置默认值为一个空对象
  },
  searchValue:String
};

export type ResultItemProps = ExtractPropTypes<typeof resultItemProps>;
export default defineComponent({
  props: resultItemProps,

  emits: ['click'],

  setup(props, { slots, emit }) {
    const title = computed(() => {
      return props.itemTemplateGeneral.find(item => {
        return item.type === 'title';
      });
    });

    const regex = computed(()=>
      new RegExp(props.searchValue, "gi")
    )

    const getVal = (item, highlight=true) => {
      let val = null;
      if (item.valueType == 'field') {
        val = props.data[item.field];
      } else {
        if (item.expression) {
          val = _template(item.expression)(props.data);
        }
      }
      return getValHighlight(val, highlight)
    };

    const getValHighlight = (val, highlight=true) => {
      if(val!=null && val!= undefined && highlight){
        return `${val}`.replace(regex.value, function(match) {
            return "<span class='t-text-ellipsis-highlight'>" + match + "</span>";
        });
      }else{
        return val;
      }
    };

    const renderTitle = () => {
      if (title.value) {
        const val = getVal(title.value);
        if (val) return (
          <div class={['t-multi-ellipsis--l2', 'title']} innerHTML={val}></div>
        );
      }
    };
    const thumb = computed(() => {
      return props.itemTemplateGeneral.find(item => {
        return item.type === 'thumb';
      });
    });

    const renderThumb = () => {
      if (slots.thumb || thumb.value) {
        const src = getVal(thumb.value, false);
        if (src) {
          return (
            <TImg
              src={src}
              style='width:var(--t-popup-search-result-item-thumb-size);height:var(--t-popup-search-result-item-thumb-size);border-radius: var(--t-popup-search-result-item-thumb-radius);'
            />
          );
        }
      }
    };

    const fields = computed(() => {
      return props.itemTemplateGeneral.filter(item => {
        return item.type === 'info';
      });
    });

    const renderFields = () => {
      if (fields.value) {
        return fields.value?.map((field: ItemTemplateGeneralType, index:number) => {
          const content = '' + getVal(field);
          const rawContent = '' + getVal(field, false);
          return field.ellipsis ? (
            <TextEllipsis
              index={index}
              class={Style.textEllipsis}
              rows={2}
              dots='...'
              expand-text='展开'
              collapse-text=''
              content={content}
              rawContent={rawContent}
              getValHighlight={getValHighlight}
              onClickAction={e => {
                e.stopPropagation();
              }}
            >
              {{
                expand() {
                  return (
                    <span class={Style.textEllipsisExpand}>
                      <TIcon name='expand_more' size="" />
                    </span>
                  );
                },
              }}
            </TextEllipsis>
          ) : (
            <TextEllipsis
              index={index}
              rows={100000}
              dots=''
              expand-text=''
              collapse-text=''
              content={content}
              rawContent={rawContent}
              getValHighlight={getValHighlight}
              onClickAction={e => {
                e.stopPropagation();
              }}
            ></TextEllipsis>
          );
        });
      }
    };

    const onHandlerClick = () => {
      emit('click');
    };
    const bem = (n?) => {
      return `t-popup-search-result-item${n ? '__' + n : ''}`;
    };

    return () => {
      return (
        <div class={bem()} onClick={onHandlerClick}>
          <div class={bem('header')}>
            {renderThumb()}
            <div class={bem('content')}>
              <div class={bem('content-item')}>
                {renderTitle()}
                {renderFields()}
              </div>
            </div>
          </div>
        </div>
      );
    };
  },
});
